﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Utility;
using Kiiro.Common.Entities;

using SPListNames = Kiiro.Common.Utility.Constants.SPListNames;
using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;
using ProjectFileUrls = Kiiro.Common.Utility.Constants.ProjectFileUrls;

namespace Kiiro.SiteDefinition.ControlTemplates
{
    public partial class NavigationSub : KiiroUserControl
    {
        private List<LinkButton> commands = new List<LinkButton> ( );
        public List<LinkButton> Commands
        {
            get { return commands; }
            set { commands = value; }
        }

        public KiiroDeleteButton DeleteButton
        {
            get { return kiiroDelete; }
        }

        public bool HasTabs { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if ( Commands.Count > 0 )
            {
                HtmlGenericControl actions = new HtmlGenericControl ( "div" );
                actions.Attributes.Add ( "class", "actions" );

                foreach ( LinkButton button in Commands )
                {
                    HtmlGenericControl ul = new HtmlGenericControl ( "ul" );
                    HtmlGenericControl li = new HtmlGenericControl ( "li" );
                    HtmlGenericControl span = new HtmlGenericControl ( "span" );
                    span.Attributes.Add ( "class", button.Attributes [ "class" ] ?? button.CssClass );
                    span.InnerText = button.Text;

                    button.CssClass = string.Empty;
                    button.Text = string.Empty;

                    button.Controls.Add ( span );
                    li.Controls.Add ( button );
                    ul.Controls.Add ( li );
                    actions.Controls.Add ( ul );
                }

                pnlTabs.Controls.Add ( actions );
            }
        }
        
        protected override void OnPreRender ( EventArgs e )
        {
            try
            {
                List<NavigationItem> tabs = new List<NavigationItem> ( );
                List<NavigationItem> navItems = new List<NavigationItem> ( );
                List<NavigationItem> projectNavItems = new List<NavigationItem> ( );

                string siteLevel = IsPortal ? "Portal" : "Project";

                try
                {
                    using ( SPWeb web = SPHelpers.GetPortalWeb ( Base.SiteCollectionId, Base.ServerRelativeUrl ) )
                    {
                        SPList list = web.Lists [ Constants.SPListNames.SubNavigation ];

                        if ( list != null )
                        {
                            navItems = list.Items.Cast<SPListItem> ( ).Select ( li => new NavigationItem ( li ) ).ToList ( );
                            navItems = navItems
                                .Where ( i => i.SiteLevel == siteLevel && i.IsVisible && i.PageDisplayCollection.Exists ( a => a.ToLower ( ) == RequestFilePath ( ) ) )
                                    .ToList ( );
                        }
                    }
                }
                catch { }

                if ( IsProject )
                {
                    try
                    {
                        using ( SPWeb web = SPHelpers.GetWeb ( Base.SiteCollectionId, Base.ServerRelativeUrl ) )
                        {
                            SPList list = web.Lists [ Constants.SPListNames.SubNavigation ];

                            if ( list != null )
                            {
                                projectNavItems = list.Items.Cast<SPListItem> ( ).Select ( li => new NavigationItem ( li ) ).ToList();
                                projectNavItems = projectNavItems
                                    .Where ( i => i.IsVisible && i.PageDisplayCollection.Exists ( a => a.ToLower ( ) == RequestFilePath ( ) ) )
                                        .ToList ( );

                                navItems.AddRange ( projectNavItems );
                            }
                        }
                    }
                    catch { }
                }

                navItems = navItems.OrderBy ( x => x.Sequence ).ThenBy ( x => x.Title ).ToList ( );

                // one-time permission checks (to reduce unnecessary overhead)
                bool isFullAdminCheck = this.Base.CurrentUser.IsAdministrator && !this.Base.CurrentUser.ManageProjectsOnly;
                bool isPortalMemberCheck = this.Base.CurrentUser.Groups.Contains(KiiroGroup.PortalMember) && this.Base.CurrentUser.Login != Constants.Security.AD_AUTH_USERS_DOMAIN_GROUP_NAME;
                bool isProjectOwnerCheck = this.Base.PermissionBitsProjects[2] || this.Base.PermissionBitsProjects[3];

                foreach (NavigationItem navItem in navItems)
                {
                    bool canAddLink = false;
                    navItem.GroupVisibility.ForEach(
                        delegate(KiiroGroup kg)
                        {
                            if (!canAddLink)
                            {
                                if (kg == KiiroGroup.PortalOwner)
                                    canAddLink = isFullAdminCheck;
                                else if (kg == KiiroGroup.PortalMember)
                                    canAddLink = isPortalMemberCheck;
                                else if (kg == KiiroGroup.ProjectOwner)
                                    canAddLink = isProjectOwnerCheck;
                                else if (kg == KiiroGroup.ProjectMember)
                                    canAddLink = true;
                                else if (kg == KiiroGroup.Visitor)
                                    canAddLink = true;
                            }
                        });

                    if (canAddLink)
                        tabs.Add(navItem);
                }

                litTabs.Text = "";
                bool edge = true;
                foreach (NavigationItem navItem in tabs)
                {
                    bool selected = IsSelected(navItem);

                    string cssClass = (selected ? "selected" + (edge ? " edge" : "") : "");
                    string tab = "<div class='tab {0}'><div class='wrap'><a {1}>{2}</a></div></div>";
                    string targetUrl = navItem.TargetUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || navItem.TargetUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? navItem.TargetUrl : String.Format("{0}{1}", Base.ServerRelativeUrl, navItem.TargetUrl);
                    string url = selected ? "" : "href='" + (navItem.TargetUrl.StartsWith("/") ? targetUrl : navItem.TargetUrl) + "'";
                    string title = navItem.Title;
                    switch (title.ToUpper())
                    {
                        case "[TITLE]":
                            if ( !string.IsNullOrEmpty ( Base.PageTitle ) )
                                title = Base.PageTitle;
                            else if ( !string.IsNullOrEmpty ( SPContext.Current.ListItemDisplayName ) )
                            {
                                title = SPContext.Current.ListItemDisplayName;
                                if ( title.ToLower ( ) == "new item" && SPContext.Current.FormContext.FormMode == SPControlMode.Display )
                                    title = SPContext.Current.List.Title;
                            }
                            break;
                        default:
                            break;
                    }
                    title = title ?? navItem.Title;
                    litTabs.Text += string.Format(tab, cssClass, url, title);

                    edge = false;
                }

                if ( Commands.Count == 0 && litTabs.Text == "" )
                {
                    pnlTabs.Style.Add ( "height", "10px" );
                }
            }
            catch (Exception ex)
            {
                ExceptionManagement.ExceptionManager.HandleException(ex, true);
            }
        }

        private bool IsSelected ( NavigationItem navItem )
        {
            string thisPage = RequestFilePath ( );
            List<string> hilite = navItem.PageHiLiteCollection;
            bool selected = hilite.Exists ( x => x.ToLower ( ) == thisPage );
            return selected;
        }

        private string RequestFilePath ( )
        {
            return Request.FilePath.Substring ( Request.FilePath.LastIndexOf ( "/" ) ).ToLower ( );
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/CONTROLTEMPLATES/Kiiro/NavigationSub.ascx.cs $
 * 
 * 23    2/24/10 4:49p Camerons
 * 
 * 22    2/12/10 10:58a Camerons
 * 
 * 21    2/12/10 9:14a Camerons
 * 
 * 20    2/08/10 2:28p Camerons
 * 
 * 19    1/07/10 2:40p Camerons
 * 
 * 18    1/07/10 12:28p Camerons
 * 
 * 17    1/06/10 10:44p Camerons
 * 
 * 16    1/06/10 12:39p Camerons
 * 
 * 15    1/04/10 11:01a Camerons
 * 
 * 14    12/23/09 3:34p Stefanf
 * 
 * 13    12/21/09 2:19p Camerons
 * 
 * 12    18/12/09 5:49p Adamw
 * 
 * 11    12/18/09 5:02p Stefanf
 * 
 * 10    12/18/09 4:35p Stefanf
 * 
 * 9     12/18/09 3:47p Stefanf
 * 
 * 8     9/11/09 12:09p Camerons
 * 
 * 7     10/26/09 9:25a Adamw
 * 
 * 6     10/23/09 5:42p Adamw
 * Case 348
 * 
 * 5     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/
